package com.jielihaofeng.site.tag.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jielihaofeng.site.article.dao.ArticleDao;
import com.jielihaofeng.site.article.entity.ArticleEntity;
import lombok.AllArgsConstructor;
import com.jielihaofeng.framework.common.exception.FastException;
import com.jielihaofeng.framework.common.page.PageResult;
import com.jielihaofeng.framework.common.service.impl.BaseServiceImpl;
import com.jielihaofeng.site.tag.convert.TagConvert;
import com.jielihaofeng.site.tag.dao.TagDao;
import com.jielihaofeng.site.tag.entity.TagEntity;
import com.jielihaofeng.site.tag.query.TagQuery;
import com.jielihaofeng.site.tag.service.TagService;
import com.jielihaofeng.site.tag.vo.TagVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 标签管理
 *
 * @author 借力好风 949394048@qq.com
 * @since 1.0.0 2022-07-21
 */
@Service
@AllArgsConstructor
public class TagServiceImpl extends BaseServiceImpl<TagDao, TagEntity> implements TagService {

    private final ArticleDao articleDao;

    @Override
    public PageResult<TagVO> page(TagQuery query) {
        IPage<TagEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(TagConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private QueryWrapper<TagEntity> getWrapper(TagQuery query) {
        QueryWrapper<TagEntity> wrapper = new QueryWrapper<>();

        return wrapper;
    }

    @Override
    public void save(TagVO vo) {
        TagEntity entity = TagConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(TagVO vo) {
        TagEntity entity = TagConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public void delete(Long id) {
        // 判断分类下面是否有文章
        long userCount = articleDao.selectCount(new QueryWrapper<ArticleEntity>().eq("category_id", id));
        if(userCount > 0){
            throw new FastException("标签下面有文章，不能删除");
        }

        removeById(id);
    }


}